package util.concurrent.delayqueue;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 6/7/2022 8:54 PM
 */
public class DelayQueueTest {

    private static final Logger logger = LoggerFactory.getLogger(DelayQueueTest.class);

    @Test
    public void test() throws InterruptedException {
        DelayDemo delayDemo1 = new DelayDemo(5l, "订单1", TimeUnit.SECONDS);
        DelayDemo delayDemo2 = new DelayDemo(10l, "订单2", TimeUnit.SECONDS);
        DelayDemo delayDemo3 = new DelayDemo(15l, "订单3", TimeUnit.SECONDS);

        DelayQueue<DelayDemo> delayQueue = new DelayQueue<>();
        delayQueue.add(delayDemo1);
        delayQueue.add(delayDemo2);
        delayQueue.add(delayDemo3);

        logger.info("延迟队列开始时间：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        while (delayQueue.size() != 0) {
            DelayDemo delayDemo = delayQueue.poll();
            if (Objects.nonNull(delayDemo)) {
                logger.info("任务：" + delayDemo.getName() + "被取消, 取消时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            Thread.sleep(1000);
        }
    }


}
